package com.ctrip.corp.obt.shard.loader.factory;


import com.ctrip.corp.obt.generic.utils.ExceptionUtils;
import com.ctrip.corp.obt.shard.constants.SourceLoadMode;
import com.ctrip.corp.obt.shard.loader.IShardSourceLoader;
import com.ctrip.corp.obt.shard.manager.DataShardSourceManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

/**
 * @author marco.zheng
 * @version 1.0
 * @date 2022/01/14
 * @desc ShardSourceLoader工厂类
 * @see
 * @since 1.0
 */
@Slf4j
@RequiredArgsConstructor
public class ShardSourceLoaderFactory {

    private final DataShardSourceManager dataShardSourceManager;

    /**
     * 根据sourceLoadMode构建loader
     * @param sourceLoadMode {@link SourceLoadMode#name()}
     * @return
     */
    public IShardSourceLoader create(String sourceLoadMode) {
        Class<? extends IShardSourceLoader> loaderClassType = SourceLoadMode.getLoaderClassType(sourceLoadMode);
        if (null == loaderClassType) {
            throw ExceptionUtils.mpe("Not found sourceLoadMode:{}, please check", sourceLoadMode);
        }
        try {
            return BeanUtils.instantiateClass(loaderClassType.getConstructor(DataShardSourceManager.class), dataShardSourceManager);
        } catch (NoSuchMethodException e) {
            throw ExceptionUtils.mpe("Initializing IShardSourceLoader failed with reason: {}", e.getMessage());
        }
    }
}
